package util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class SMSSender {

    // 短信发送接口URL
    private static final String SMS_SEND_URL = "http://120.46.73.73:11002/api/SMSSendApi/SendPort";

    // 账户信息
    private static final String ACCOUNT = "信息室";
    private static final String PWD = "123";

    public static String sendSMS(String missionName, String groupNames, String departmentNames, String tmpPhoneNum, String content) throws Exception {
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(SMS_SEND_URL);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");

            // 创建请求体
            Map<String, String> requestParams = new HashMap<>();
            requestParams.put("Account", ACCOUNT);
            requestParams.put("Pwd", PWD);
            requestParams.put("SMSMissionNames", missionName);
            //requestParams.put("GroupNames", groupNames);
            //requestParams.put("DepartmentNames", departmentNames);
            requestParams.put("TmpPhoneNum", tmpPhoneNum);
            requestParams.put("Content", content);

            // 将请求体转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(requestParams);
            System.out.println(requestBody);

            // 设置请求体到HttpPost对象中
            StringEntity entity = new StringEntity(requestBody, "UTF-8");
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
                return responseBody; // 返回响应体，可根据需要解析
            }
        }
    }

    public static void main(String[] args) {
        try {
            String missionName = "测试任务";
            String groupNames = "测试群组";
            String departmentNames = "测试部门";
            String tmpPhoneNum = "15117910426";
            String content = "这是一条测试短信";

            String response = sendSMS(missionName, groupNames, departmentNames, tmpPhoneNum, content);
            System.out.println("响应内容: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
